<?php

namespace app\mec\controller;

use think\Controller;
use think\File;
use think\Request;
use think\Seeeion;
use think\Db;
use org\Qiniu;
use org\Upayun;

use Qiniu\Auth;// 引入鉴权类
use Qiniu\Storage\UploadManager;// 引入上传类
use Qiniu\Processing\PersistentFop;
require_once('../extend/qiniu/autoload.php');

class Upload extends Base
{
    /**
     * 上传图片到又拍云
     * @throws \Exception
     */
    public function uploads()
    {
        $filePath = $_FILES['file']['tmp_name'];
        //取出图片后缀
        $type = explode(".", $_FILES['file']['name']);
        $type = end($type);
        //组装图片名
        $key = md5(time() . uuid()) . '.' . $type;
        $up = new Upayun();
        $data = $up->uploadFile($filePath, $key, '/up/', 'http://image-kevin.test.upcdn.net');
        echo $data;
    }
    
    /**
     * 删除又拍云图片文件
     * @return \think\response\
     */
    public function deleteImg()
    {
        $add = input('add');
        $up = new Upayun();
        $res = $up->delFile($add, 'http://image-kevin.test.upcdn.net');
        if($res) {
            return json(['code' => 200, 'msg' => '删除成功！']);
        } else {
            return json(['code' => 100, 'msg' => '删除失败！']);
        }
    }
    
    /**
     * deleteImg 删除七牛图片文件
     * @return \think\response\
     */
    public function deleteImgs()
    {
        $add = input('add');
        $add = str_replace('http://qiniu.verynurse.com/', '', $add);
        $up = new Qiniu();
        $res = $up->delFile($add, 'nanding');
        if($res) {
            return json(['code' => 100, 'msg' => '删除失败！']);
        } else {
            return json(['code' => 200, 'msg' => '删除成功！']);
        }
    }
    
    /**
     * 删除本地视频
     * @return \think\response\Json
     */
    public function deleteImgBendi()
    {
        $add = input('add');
        $filePath = $_SERVER['DOCUMENT_ROOT']. DS . $add;
        $res = @unlink($filePath);
        if($res) {
            return json(['code' => 100, 'msg' => '删除失败！']);
        } else {
            return json(['code' => 200, 'msg' => '删除成功！']);
        }
    }
    
    
    /**
     * upload 上传图片到七牛云
     * @throws \Exception
     */
    public function upload()
    {
        set_time_limit (0);
        $filePath = $_FILES['file']['tmp_name'];
        //取出图片后缀
        $type = explode(".", $_FILES['file']['name']);
        $type = end($type);
        //组装图片名
        $key = md5(time() . uuid()) . '.' . $type;
        $up = new Qiniu();
        $data = $up->uploadFile($filePath, $key, 'http://qiniu.verynurse.com/');
        echo $data;

//        $code  = GetRandCode();
//        alisms('13057633126',$code);
//        YzxSms($code,'13057633126',1);
        
        
        //水印
//        $image = \org\Image::open('static/admin/images/zzzzz.jpg');
//        $image->water('static/admin/images/eqcode.png',1)->save('static/admin/images/water_image.png');
//        header("Content-type:text/html;charset=utf-8");
    }
    
    /**
     * uploadLocality图片上传至本地&压缩
     */
    public function uploadsss()
    {
        $file = request()->file('file');
        $dir = ROOT_PATH . 'public' . DS . 'uploads/images';
        if(!file_exists($dir)) {
            //检查是否有该文件夹，如果没有就创建，并给予最高权限
            mkdir($dir, 0700, true);
        }
        $url = "http://" . $_SERVER['HTTP_HOST'];
        $info = $file->move($dir);
        if($info) {
            $newName = $info->getSaveName();
            //压缩图片
            image_png_size_add(ROOT_PATH . 'public' . DS . 'uploads/images/' . $newName, ROOT_PATH . 'public' . DS . 'uploads/images/' . $newName);
            echo "{$url}/uploads/images/{$newName}";
        } else {
            echo $file->getError();
        }
    }
    
    /**
     * video 视频文件上传至本地
     */
    public function video()
    {
        @set_time_limit(5 * 60);
        $targetDir = ROOT_PATH . 'public' . DS . 'uploads/video_tmp';
        $uploadDir = ROOT_PATH . 'public' . DS . 'uploads/video/' . date('Ymd');
        $cleanupTargetDir = true; // Remove old files
        $maxFileAge = 5 * 3600; // Temp file age in seconds
// Create target dir
        if(!file_exists($targetDir)) {
            @mkdir($targetDir, 0700, true);
        }

// Create target dir
        if(!file_exists($uploadDir)) {
            @mkdir($uploadDir, 0700, true);
        }

// Get a file name
        if(!empty($_FILES)) {
            $fileName = urlencode($_FILES["file"]["name"]);
        } else {
            $fileName = uniqid("file_");
        }
        
        $filePath = $targetDir . DS . iconv("UTF-8", "gb2312", $fileName);
//        $uploadPath = $uploadDir . DS . iconv("UTF-8","gb2312",$fileName);

// Chunking might be enabled
        $chunk = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0;
        $chunks = isset($_REQUEST["chunks"]) ? intval($_REQUEST["chunks"]) : 1;

// Remove old temp files
        if($cleanupTargetDir) {
            if(!is_dir($targetDir) || !$dir = opendir($targetDir)) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 100, "message": "Failed to open temp directory."}, "id" : "id"}');
            }
            
            while(($file = readdir($dir)) !== false) {
                $tmpfilePath = $targetDir . DS . $file;
                
                // If temp file is current file proceed to the next
                if($tmpfilePath == "{$filePath}_{$chunk}.part" || $tmpfilePath == "{$filePath}_{$chunk}.parttmp") {
                    continue;
                }
                
                // Remove temp file if it is older than the max age and is not the current file
                if(preg_match('/\.(part|parttmp)$/', $file) && (@filemtime($tmpfilePath) < time() - $maxFileAge)) {
                    @unlink($tmpfilePath);
                }
            }
            closedir($dir);
        }


// Open temp file
        if(!$out = @fopen("{$filePath}_{$chunk}.parttmp", "wb")) {
            die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
        }
        
        if(!empty($_FILES)) {
            if($_FILES["file"]["error"] || !is_uploaded_file($_FILES["file"]["tmp_name"])) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}');
            }
            // Read binary input stream and append it to temp file
            if(!$in = @fopen($_FILES["file"]["tmp_name"], "rb")) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
            }
        } else {
            if(!$in = @fopen("php://input", "rb")) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
            }
        }
        while($buff = fread($in, 4096)) {
            fwrite($out, $buff);
        }
        @fclose($out);
        @fclose($in);
        rename("{$filePath}_{$chunk}.parttmp", "{$filePath}_{$chunk}.part");
        $index = 0;
        $done = true;
        for($index = 0; $index < $chunks; $index++) {
            if(!file_exists("{$filePath}_{$index}.part")) {
                $done = false;
                break;
            }
        }
        
        if($done) {
            $name = uuid();
//            if (!file_exists($uploadDir . DS . $name)) {
            @mkdir($uploadDir . DS . $name, 0700, true);
//            }
            $uploadPath = $uploadDir . DS . $name . DS . iconv("UTF-8", "gb2312", $fileName);
            if(!$out = @fopen($uploadPath, "wb")) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
            }
            
            if(flock($out, LOCK_EX)) {
                for($index = 0; $index < $chunks; $index++) {
                    if(!$in = @fopen("{$filePath}_{$index}.part", "rb")) {
                        break;
                    }
                    
                    while($buff = fread($in, 4096)) {
                        fwrite($out, $buff);
                    }
                    
                    @fclose($in);
                    @unlink("{$filePath}_{$index}.part");
                }
                
                flock($out, LOCK_UN);
            }
            @fclose($out);
            echo 'uploads/video/' . date('Ymd') . '/' . $name . '/' . $fileName;
        }
    }
    
    /**
     * deleteFile 循环删除文件
     * @return \think\response\Json
     */
    public function deleteFile()
    {
//        $adds = explode('/',input('add'));
//        array_pop($adds);
//        $add = implode('/',$adds);
//        if(delete_dir_file(ROOT_PATH  . 'public' . DS .$add)){
//            return json(['code'=>200,'msg'=>'删除成功']);
//        }else{
//            return json(['code'=>100,'msg'=>'删除失败']);
//        }
    }
    
    
    //会员头像上传
    public function uploadface()
    {
        $file = request()->file('file');
        $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads/face');
        if($info) {
            echo $info->getSaveName();
        } else {
            echo $file->getError();
        }
    }
    
    //后台用户修改头像上传
    public function updateFace()
    {
        $base64url = input('base64url');
        //匹配出图片的格式
        $base64url = str_replace(' ', '+', $base64url);
        if(preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64url, $result)) {
            $type = $result[2];
            $new_file = ROOT_PATH . 'public' . DS . 'uploads/face/' . date('Ymd', time()) . "/";
            if(!file_exists($new_file)) {
                //检查是否有该文件夹，如果没有就创建，并给予最高权限
                mkdir($new_file, 0700, true);
            }
            $new_file = $new_file . time() . ".{$type}";
            if(file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64url)))) {
                $new = md5(time());
                image_png_size_add($new_file, ROOT_PATH . 'public' . DS . 'uploads/face/' . date('Ymd', time()) . "/" . $new . ".{$type}");
                $url = "http://" . $_SERVER['HTTP_HOST'];
                $file_name = $url . "/uploads/face/" . date('Ymd', time()) . "/" . $new . ".{$type}";
                $res = Db::name('admin')->where('id', input('id'))->update(["portrait" => $file_name]);
                unlink($new_file);
                if($res) {
                    session('portrait', $file_name); //用户头像
                    return json(['code' => 200, 'msg' => "上传成功"]);
                } else {
                    return json(['code' => 100, 'msg' => "上传失败"]);
                }
            } else {
                return json(['code' => 100, 'msg' => "上传失败"]);
            }
        } else {
            return json(['code' => 100, 'msg' => "图片信息错误"]);
        }
    }
    
    //多图修改测试页面
    public function showImg()
    {
        $photo = Db::name('img')->where('id', 1)->value('img');
        $arr = explode(',', $photo);
        $this->assign('photo', $photo);
        $this->assign('arr', $arr);
        return $this->fetch('/webuploader2');
    }
}